export default class IndexStorage {
  constructor() {
    this.indexedDB = window.indexedDB;
  }

  async initRequest() {
    this.name = 'THREEX-POC';
    this.version = 1;
    this.database = null;
    this.request = this.indexedDB.open(this.name, this.version);
    const that = this;
    return new Promise((r, e) => {
      this.request.onupgradeneeded = function (event) {

        //@ts-ignore
        const db = event.target.result;
        if (db.objectStoreNames.contains('states') === false) {
          db.createObjectStore('states');
        }
      }
      this.request.onsuccess = function (event) {

        //@ts-ignore
        that.database = event.target.result;
        r(true)
      };

      this.request.onerror = function (event) {
        console.error('IndexedDB', event);
        r(true)
      };
    })
  }

  init(callback) {

  }

  get(callback,name) {
    const transaction = this.database.transaction(['states'], 'readwrite');
    const objectStore = transaction.objectStore('states');

    const request = objectStore.get(name || 0);
    request.onsuccess = function (event) {
      callback && callback(event.target.result);
    }
  }

  set(data, name = null) {
    const start = performance.now();

    const transaction = this.database.transaction(['states'], 'readwrite');
    const objectStore = transaction.objectStore('states');
    const request = objectStore.put(data, name || 0);
    request.onsuccess = function () {
      console.log('Saved state to IndexedDB. ' + (performance.now() - start).toFixed(2) + 'ms');
    };

  }

  clear() {

    if (database === undefined) return;
    const transaction = this.database.transaction(['states'], 'readwrite');
    const objectStore = transaction.objectStore('states');
    const request = objectStore.clear();
    this.request.onsuccess = function () {
      console.log('Cleared IndexedDB.');
    };
  }

  setLocalStorage(key,content){
    localStorage.setItem(
      key,
      JSON.stringify({
        expir: Date.now() + 1000 * 60 * 60 * 8,
        value: content
      })
    )
  }

  getLocalStorage(key){
    try {
      const result = JSON.parse(localStorage.getItem(key) || '{}');
      if (result.hasOwnProperty('value')) {
        return result.value;
      } else {
        return result;
      }
    } catch (error) {
  
    }
  }
} 
